/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

 //分治
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode*slow=head,*fast=head;
        ListNode*pre=head;
        while(fast&&fast->next)
        {
            pre=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        pre->next=nullptr;
        head=sortList(head);
        slow=sortList(slow);

        return mergetwolists(head,slow);
    }
    ListNode* mergetwolists(ListNode*list1,ListNode*list2)
    {
        ListNode*newnode = new ListNode(0);
        ListNode*cur=newnode;
        while(list1&&list2)
        {
            if(list1->val<list2->val)
            {
                cur->next=list1;
                list1=list1->next;
            }
            else
            {
                cur->next=list2;
                list2=list2->next;
            }
            cur=cur->next;
        }
        cur->next=list1?list1:list2;
        return newnode->next;
    }
};
